package getway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthGatewayFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(
            ServerWebExchange exchange,
            GatewayFilterChain chain) {
        //获取请求参数
        String token =exchange.getRequest().getQueryParams().getFirst("token");
        //处理业务逻辑
        if(token!=null){
            //处理结果
            return chain.filter(exchange);
        }else{
            ServerHttpResponse response = exchange.getResponse();
            //设置头参数
            response.getHeaders().add("Content-Type","application/json;charset=utf-8");
            //设置影响状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String msg ="{'msg:\"登录失败\"}";
            DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
            //返回数据
            return response.writeWith(Mono.just(buffer));
        }
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
